<template>
    <el-dialog :visible.sync="visible" title="上传文件" width="30%" @close="handleCancel">
        <el-upload :action="uploadAction" :on-success="handleSuccess" :on-error="handleError" :file-list="fileList"
            :auto-upload="false" ref="uploadRef">
            <el-button slot="trigger" type="primary">选择文件</el-button>
            <el-button slot="trigger" type="primary">下载模板</el-button>
            <div slot="tip">仅支持 .xls 和 .xlsx 文件</div>
        </el-upload>

        <span slot="footer">
            <el-button @click="handleCancel">取消</el-button>
            <el-button type="primary" @click="handleUpload">上传</el-button>
        </span>
    </el-dialog>
</template>

<script>
export default {
    name: "UploadDialog",
    props: {
        visible: {
            type: Boolean,
            required: true,
        },
    },
    data() {
        return {
            /**
             * 文件列表
             * @type {Array}
             */
            fileList: [],

            /**
             * 上传地址
             * @type {String}
             */
            uploadAction: "http:///upload", 
        };
    },
    methods: {
        /**
         * 成功回调
         * @param {Object} response - 服务端返回数据
         * @param {Object} file - 当前上传的文件
         * @returns {void}
         */
        handleSuccess(response, file) {
            this.$message.success(`${file.name} 上传成功`);
            this.fileList = [];
            this.$emit("", response);
        },

        /**
         * 上传失败回调
         * @param {Object} err - 错误信息
         * @param {Object} file - 当前上传的文件
         * @returns {void}
         */
        handleError(err, file) {
            this.$message.error(`${file.name} 上传失败`);
            this.$emit("upload-error", err);
        },

        /**
         * 取消弹窗
         * @returns {void}
         */
        handleCancel() {
            this.fileList = [];
            this.$emit("update:visible", false);
        },

        /**
         * 手动触发上传
         * @returns {void}
         */
        handleUpload() {
            if (!this.fileList.length) {
                this.$message.warning("请先选择文件");
                return;
            }
            this.$refs.uploadRef.submit();
        },
    },
};
</script>

<style lang="scss" scoped></style>